/*
 * j4Win
 *  http://code.google.com/p/j4win/
 *
 * Copyright (C) 2006-2007 Felix Geyer, Moritz Laschinger
 *
 * This file is part of j4Win.
 *
 * j4Win is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * j4Win is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package j4win;

abstract public class Game implements NetworkListener {
	protected GUI gui;
	protected Network net;
	protected Field field = new Field();
	
	public enum PlayerType { Local, KI, NetworkClient, NetworkServer };
	
	protected PlayerType[] players = new PlayerType[2];
	protected KI[] ki = new KI[2];
	
	private PlayerListener[] playerListeners = new PlayerListener[2];
	
	abstract protected void playerMove(int p, int col);
	
	public Game(GUI gui, PlayerType p1, PlayerType p2, KI[] ki) {
		this.gui = gui;
		
		players[0] = p1;
		players[1] = p2;
		for (int i=0; i<ki.length; ++i) {
			this.ki[i] = ki[i];
		}
		
		playerListeners[0] = new PlayerListener() {
			public void move(int col) {
				playerMove(1, col);
			}
		};
		
		playerListeners[1] = new PlayerListener() {
			public void move(int col) {
				playerMove(2, col);
			}
		};
	}
	
	public abstract void start();
	
	protected void requestMove(int player, int lastCol) {
		switch (players[player-1]) {
			case Local:
				gui.requestMove(player, playerListeners[player-1]);
				break;
			case KI:
				Field f = field.clone();
				if (player == 2)
					f.swap();
				ki[player-1].requestMove(f, playerListeners[player-1], lastCol);
				break;
		}
	}
	
	protected void endGame(boolean isNetwork) {
		if (isNetwork)
			net.send(new NetPacket(NetPacket.ID.Close));
		
		if (ki[0] != null)
			ki[0].stop();
		
		if (ki[1] != null)
			ki[1].stop();
	}
}
